package com.md.common.utils.qq;

import com.md.common.exception.BaseBizException;
import com.md.common.utils.qq.model.QQConAccessToken;
import com.md.common.utils.qq.model.QQOpenid;
import com.md.common.utils.qq.model.QQUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 功能描述：qq互联接口处理器
 *
 * @author lujianping@oak168.com
 * @version 1.0
 * @date 2018-9-03 15:29
 * @since JDK 1.8
 */
@Component("qqConnectApiHandler")
public class QQConnectApiHandler {

    @Autowired
    private QQConnectApiProxy qqConnectApiProxy;
//    @Autowired
//    private RedisOperator redisOperator;

    public String getOauthAccessToken(String code) throws BaseBizException {
        //从缓存获取，缓存不存在则调微信接口刷新access token
        synchronized (QQConAccessToken.class){
            QQConAccessToken qqConAccessToken = qqConnectApiProxy.getOauthAccessToken(code);
            return qqConAccessToken.getAccess_token();
        }
    }

    @Deprecated
    public String getOauthAccessToken2(String code) throws BaseBizException {
        //从缓存获取，缓存不存在则调微信接口刷新access token
        synchronized (QQConAccessToken.class){
            QQConAccessToken qqConAccessToken = null;
//            String qqConAccessTokenStr = redisOperator.getString(RedisKeyConst.QQ_CONNECT_ACCESS_TOKEN_PREFIX + code);
//            if(StringUtils.isNotEmpty(qqConAccessTokenStr)){
//                qqConAccessToken = JSONUtil.toBean(qqConAccessTokenStr, QQConAccessToken.class);
//            }
//            if(qqConAccessToken == null){
//                qqConAccessToken = qqConnectApiProxy.getOauthAccessToken(code);;
//                redisOperator.setString(RedisKeyConst.QQ_CONNECT_ACCESS_TOKEN_PREFIX + code, JSONUtil.toJSON(qqConAccessToken), qqConAccessToken.getExpires_in() - 300);
//            }
            return qqConAccessToken.getAccess_token();
        }
    }

    public String getOpenId(String accessToken) throws BaseBizException {
        QQOpenid qqOpenid = qqConnectApiProxy.getOpenId(accessToken);
        return qqOpenid != null? qqOpenid.getOpenid() : null;
    }

    public QQUserInfo getUserInfo(String accessToken, String openid) throws BaseBizException {
        QQUserInfo qqUserInfo = qqConnectApiProxy.getUserInfo(accessToken, openid);
        return qqUserInfo;
    }
}
